using System;
using System.Collections.ObjectModel;
using System.Windows;
using System.Windows.Input;
using WPF_MVVM_Test.MVVM_Model;
using WPF_MVVM_Test.Services;
using System.Threading.Tasks; // Added for Task.Delay

namespace WPF_MVVM_Test.MVVM_ViewModel
{
    public class ChatViewModel : BaseViewModel
    {
        private readonly AiChatService _chatService;
        private string _currentMessage = string.Empty;
        private bool _isAiTyping = false;
        private ChatMessage? _currentAiMessage;

        public ChatViewModel()
        {
            _chatService = new AiChatService();
            ChatMessages = new ObservableCollection<ChatMessage>();
            
            SendMessageCommand = CreateCommand(ExecuteSendMessage, () => CanSendMessage);
            ClearChatCommand = CreateCommand(ExecuteClearChat);

            AddWelcomeMessage();
        }

        public ObservableCollection<ChatMessage> ChatMessages { get; }

        public string CurrentMessage
        {
            get => _currentMessage;
            set 
            { 
                SetProperty(ref _currentMessage, value);
                OnPropertyChanged(nameof(CanSendMessage));
            }
        }

        public bool IsAiTyping
        {
            get => _isAiTyping;
            set 
            { 
                SetProperty(ref _isAiTyping, value);
                OnPropertyChanged(nameof(CanSendMessage));
            }
        }

        public bool CanSendMessage => !string.IsNullOrWhiteSpace(CurrentMessage) && !IsAiTyping;

        public ICommand SendMessageCommand { get; }
        public ICommand ClearChatCommand { get; }

        private void AddWelcomeMessage()
        {
            ChatMessages.Add(new ChatMessage
            {
                Content = "您好！我是您的AI智能助手，有什么可以帮助您的吗？",
                IsUser = false,
                Timestamp = DateTime.Now
            });
        }

        private async void ExecuteSendMessage()
        {
            if (string.IsNullOrWhiteSpace(CurrentMessage))
                return;

            var userMessage = CurrentMessage.Trim();
            CurrentMessage = string.Empty;

            // 添加用户消息
            ChatMessages.Add(new ChatMessage
            {
                Content = userMessage,
                IsUser = true,
                Timestamp = DateTime.Now
            });

            IsAiTyping = true;

            // 创建一个新的AI消息占位符
            _currentAiMessage = new ChatMessage
            {
                Content = "思考中...", // 初始显示加载中
                IsUser = false,
                Timestamp = DateTime.Now
            };
            ChatMessages.Add(_currentAiMessage);
            
            // 强制更新UI
            OnPropertyChanged(nameof(ChatMessages));

            try
            {
                System.Diagnostics.Debug.WriteLine($"发送消息: {userMessage}");
                
                var request = new ChatRequest
                {
                    content = userMessage,
                    botId = "7524702072735367168",
                    userId = "123",
                    conversationId = "123",
                    stream = false,
                    autoSaveHistory = true
                };

                // 设置超时 - 增加到10分钟
                var timeoutTask = Task.Delay(600000); // 10分钟 = 600000毫秒
                var requestTask = _chatService.SendMessageStreamAsync(
                    request,
                    OnDataReceived,
                    OnCompleted,
                    OnError
                );
                
                // 等待请求完成或超时
                if (await Task.WhenAny(requestTask, timeoutTask) == timeoutTask)
                {
                    // 请求超时
                    System.Diagnostics.Debug.WriteLine("请求超时");
                    OnError(new TimeoutException("请求超时，服务器响应时间过长。"));
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"发送消息异常: {ex}");
                OnError(ex);
            }
        }

        private void OnDataReceived(string data)
        {
            // 确保在UI线程上执行
            Application.Current.Dispatcher.Invoke(() =>
            {
                System.Diagnostics.Debug.WriteLine($"收到AI回复: '{data}'");
                
                if (_currentAiMessage != null)
                {
                    if (!string.IsNullOrWhiteSpace(data))
                    {
                        // 直接更新当前消息内容
                        _currentAiMessage.Content = data;
                        
                        // 强制通知UI更新
                        OnPropertyChanged(nameof(ChatMessages));
                        
                        System.Diagnostics.Debug.WriteLine("AI消息已更新");
                    }
                    else
                    {
                        _currentAiMessage.Content = "抱歉，我暂时无法回答这个问题。";
                        OnPropertyChanged(nameof(ChatMessages));
                    }
                }
            });
        }

        private void OnCompleted()
        {
            Application.Current.Dispatcher.Invoke(() =>
            {
                IsAiTyping = false;
                
                // 确保消息不为空
                if (_currentAiMessage != null)
                {
                    // 如果内容仍然是"思考中..."，说明没有收到有效回复
                    if (_currentAiMessage.Content == "思考中...")
                    {
                        _currentAiMessage.Content = "抱歉，我没有找到合适的回答。";
                        
                        // 强制通知UI更新
                        OnPropertyChanged(nameof(ChatMessages));
                        
                        System.Diagnostics.Debug.WriteLine("完成时消息为空，设置默认内容");
                    }
                    else
                    {
                        System.Diagnostics.Debug.WriteLine($"完成时消息内容: {_currentAiMessage.Content}");
                    }
                }
                
                _currentAiMessage = null;
                System.Diagnostics.Debug.WriteLine("AI回复完成");
            });
        }

        private void OnError(Exception ex)
        {
            Application.Current.Dispatcher.Invoke(() =>
            {
                IsAiTyping = false;
                
                System.Diagnostics.Debug.WriteLine($"发生错误: {ex.Message}");
                
                if (_currentAiMessage != null)
                {
                    // 在消息中显示错误
                    _currentAiMessage.Content = $"抱歉，发生了错误：{ex.Message}";
                    OnPropertyChanged(nameof(ChatMessages));
                }
                else
                {
                    // 如果当前没有消息，创建一个新的错误消息
                    ChatMessages.Add(new ChatMessage
                    {
                        Content = $"抱歉，发生了错误：{ex.Message}",
                        IsUser = false,
                        Timestamp = DateTime.Now
                    });
                    OnPropertyChanged(nameof(ChatMessages));
                }
                
                // 不显示弹窗，避免打断用户体验
                // MessageBox.Show($"AI聊天服务出现错误：{ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                _currentAiMessage = null;
            });
        }

        private void ExecuteClearChat()
        {
            var result = MessageBox.Show(
                "确定要清空所有聊天记录吗？\n\n此操作无法撤销。",
                "清空确认",
                MessageBoxButton.YesNo,
                MessageBoxImage.Question
            );

            if (result == MessageBoxResult.Yes)
            {
                ChatMessages.Clear();
                AddWelcomeMessage();
            }
        }
    }
}